package login;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class UserLoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
		
		String id=request.getParameter("id"); 
		String psw=request.getParameter("psw"); 

		HttpSession session=request.getSession();//获取session，获取不到就自己创建一个session，存在于服务器端
		session.setAttribute("uid", id);
		try {
			String sql="select * from user where userid=? and password=?";
			Class.forName("com.mysql.jdbc.Driver");
			String url="jdbc:mysql://localhost:3306/research?characterEncoding=utf-8";
			Connection con=DriverManager.getConnection(url,"root","123456");
			PreparedStatement pre=con.prepareStatement(sql);
			pre.setString(1, id);
			pre.setString(2, psw);
			pre.execute();
			ResultSet res=pre.executeQuery();
			boolean t =res.next();
			if(!t){
				RequestDispatcher dis=request.getRequestDispatcher("Userfail.jsp");
				dis.forward(request, response);
			}
			else{
				request.setAttribute("id", id);
				RequestDispatcher dis=request.getRequestDispatcher("Usersuccess.jsp");
				dis.forward(request, response);
			}
			con.close();
			
		} catch (Exception e) {
			
			e.printStackTrace();
		} 
	
	}

}
